package com.glodon.paas.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.glodon.paas.util.asyn.AsynWorker;

/**
 * 邮件发送类
 * 
 * @author huangc
 *
 */
public class SpringMailSender {
	Logger logger = LoggerFactory.getLogger(SpringMailSender.class);

	private JavaMailSender javaMailSender;
	private VelocityEngine velocityEngine;	
	private String defaultEncoding;
	private String defaultFrom;
	private String mailTemplateDir;
	private boolean enable = true;;

	AsynWorker asynWorker;
	//private ExecutorService execotor; 
	
	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	

	public void init(){
		if(javaMailSender == null){			
			// JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
			// javaMailSenderImpl.setDefaultEncoding(defaultEncoding);
			// javaMailSenderImpl.setUsername("username");
			// javaMailSenderImpl.setPassword("password");
			// javaMailSenderImpl.setHost("smtp.163.com");
			// javaMailSenderImpl.setPort(23);
			// Properties prop = new Properties();
			// // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
			// prop.put("mail.smtp.auth", "true");
			// prop.put("mail.smtp.timeout", "25000");
			// javaMailSenderImpl.setJavaMailProperties(prop);
			// javaMailSender = javaMailSenderImpl;	
		}
		if(asynWorker == null){
			//execotor = Executors.newCachedThreadPool();
		}
	}

	/**
	 * send email synchronously 
	 * @param mailContent
	 */
	public void send(SpringMailMessage mailContent) {
		if(!enable){
			logger.warn("send mail enable is false");
			return;
		}
		if(mailContent == null){
			return;
		}
		try {			
			MimeMessage msg = buildMessage(mailContent);
			javaMailSender.send(msg);
			logger.info("send mail success:"+mailContent.getSubject());
		} catch (Exception e) {
			logger.error("send mail error:"+mailContent.getSubject(), e);
			//throw new RuntimeException(e);
		}
	}
	
	/**
	 * send email in asynchronous manner
	 * @param mailContent
	 */
	public void sendAsync(SpringMailMessage mailContent) {
		try {
			if(asynWorker!=null){
				asynWorker.submit(this, "send", new Object[]{mailContent}, new Class[]{SpringMailMessage.class});
			}else{
				logger.warn("不能异步发送邮件，采用同步方式发送");
				send(mailContent);
			}
		} catch (Exception e) {
			logger.error("sendAsync error!", e);
			//throw new RuntimeException(e);
		}
	} 
 
	// 这里只能从类路径加载
	private MimeMessage buildMessage(SpringMailMessage mailContent) throws MessagingException {
		// 抬头
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper message = new MimeMessageHelper(msg, true, defaultEncoding);
		//message.setFrom(mailContent.getFrom()== null ? defaultFrom : mailContent.getFrom());
		message.setFrom(defaultFrom);
		message.setTo(mailContent.getTo());

		// 正文
		message.setSubject(mailContent.getSubject());
		String text = mailContent.getText();		
		if(text == null || text.length() == 0){
			// 从模板生产正文
			String templateLocation = mailContent.getTemplateLocation();			
			if(templateLocation != null && templateLocation.length() > 0){
				text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, defaultEncoding, mailContent.getTemplateParam());
			}
		}
		
		if(text == null){
			logger.warn("sendMail,text is null");
		}
		
		message.setText(text, mailContent.isTextHtml());		
		return msg;
	}
	
	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public String getDefaultEncoding() {
		return defaultEncoding;
	}

	public void setDefaultEncoding(String defaultEncoding) {
		this.defaultEncoding = defaultEncoding;
	}

	public String getDefaultFrom() {
		return defaultFrom;
	}

	public void setDefaultFrom(String defaultFrom) {
		this.defaultFrom = defaultFrom;
	}

	public String getMailTemplateDir() {
		return mailTemplateDir;
	}

	public void setMailTemplateDir(String mailTemplateDir) {
		this.mailTemplateDir = mailTemplateDir;
	}

	public void setAsynWorker(AsynWorker asynWorker) {
		this.asynWorker = asynWorker;
	}
}
